<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>生成发料单</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="issue-note">
      <div>
        <search-btn-view immediate btn-text="物料查询" @before-open="resetSearch" @search="searchData">
          <template slot="append">
            <el-cascader style="width:300px;margin-left:20px;" size="medium" :options="deptWorkshopList" v-model="saveData.deptAndWork"
              :props="{value:'dataId',label:'name'}" separator="-" :filterable="true" placeholder="请选择发料给车间的人员">
            </el-cascader>
            <el-button type="primary" size="medium" @click="save('workshop')">发料到车间</el-button>
            <el-button type="primary" size="medium" @click="save('outOrder')">发料到外协</el-button>
            <el-button type="primary" size="medium" @click="putToOutsource">外协审核过账</el-button>
          </template>
          <div slot="search-content">
            <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:9}" :search="search"
              :search-field="searchField" label-width="auto" input-width="200px">
              <template slot="append">
                <el-form-item label="是否有库存">
                  <el-select style="width:200px" clearable v-model="search.isValid" placeholder="请选择是否有库存">
                    <el-option :value="0" label="无库存数"></el-option>
                    <el-option :value="1" label="有库存数"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否订单发料">
                  <el-select style="width:200px" clearable v-model="search.hairFeedType" placeholder="请选择是否有库存">
                    <el-option :value="1" label="订单发料"></el-option>
                    <el-option :value="2" label="无订单发料"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </sys-common-search>
          </div>
        </search-btn-view>
      </div>
      <div class="materialToOrder">
        <span style="color:#409eff">无订单物料若要出库给订单,可选择部门,车间,人员后点击物料信息后进行操作</span>
        <span style="color:#999; margin-left:10px">当前订单采购单未审核</span>
        <span style="color:#dd514c;margin-left:10px">当前订单库存数不足</span>
      </div>
      <el-table class="materialDataListTable" fit border :data="materialDataList" height="parent" @selection-change="checkOrder" @row-click="rowClick"
        :cell-class-name="getCellClassName">
        <el-table-column sortable prop="companyOrderId" label="订单编号" min-width="140px" header-align="center" fixed="left">
        </el-table-column>
        <el-table-column sortable prop="factoryNo" label="工厂型号" min-width="100px" header-align="center" fixed="left">
        </el-table-column>
        <el-table-column sortable prop="articleNo" label="客户型号" min-width="100px" header-align="center" fixed="left">
        </el-table-column>
        <el-table-column sortable prop="providerName" label="供应商" min-width="100px" header-align="center" fixed="left">
        </el-table-column>
        <el-table-column sortable prop="materialName" label="物料名称" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable prop="materialType" label="物料类型" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable prop="color" label="编号" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable prop="colorDescription" label="描述" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable prop="model" label="规格" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable prop="materialDeptName" label="物料部门" min-width="100px" align="center">
        </el-table-column>
        <el-table-column sortable prop="providerNo" label="供方编号" min-width="100px" header-align="center">
        </el-table-column>
        <el-table-column sortable show-overflow-tooltip prop="feedCount" label="投料数" min-width="140px" header-align="center">
          <template slot-scope="scope">
            <div class="table-count" v-if="scope.row.feedCount!==null">
              <div style="flex:2">{{scope.row.feedCount}}</div>
              <div style="flex:1;margin-left:3px">{{scope.row.unit}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable prop="warehouseCount" label="库存数" min-width="140px" header-align="center">
          <template slot-scope="scope">
            <div class="table-count" v-if="scope.row.warehouseCount!==null">
              <div style="flex:2">{{scope.row.warehouseCount}}</div>
              <div style="flex:1;margin-left:3px">{{scope.row.unit}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable prop="unitPrice" label="出库单价" min-width="100px" align="center">
        </el-table-column>
        <el-table-column prop="sumPrice" label="总价" min-width="100px" align="center">
          <template slot-scope="scope">
            {{getSumPrice(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column :resizable="false" prop="receiveCount" label="发料数" width="160px" header-align="center">
          <template slot-scope="scope" v-if="scope.row.receiveCount!==null">
            <el-input-number size="mini" :controls="false" v-model="scope.row.receiveCount" style="width:110px" :is-decimal-zero="true"
              :precision="scope.row.precision" :min="0" :max="scope.row.receiveMaxCount" @change="receiveCountChange(scope.row)" @click.native.stop>
            </el-input-number>
            <span>{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderTotal" label="订单数" min-width="100px" align="center">
        </el-table-column>
        <el-table-column prop="feedTotal" label="订单投料数" min-width="100px" align="center">
        </el-table-column>
        <el-table-column :resizable="false" prop="selfOutFuCount" label="交接数(付)" width="110px" header-align="center">
          <template slot-scope="scope" v-if="scope.row.selfOutFuCount!==null">
            <div v-if="scope.row.singleFeedCount!==null" style="text-align:center">{{scope.row.selfOutFuCount}}</div>
            <el-input-number v-else size="mini" :controls="false" v-model="scope.row.selfOutFuCount" :min="1" :precision="0" style="width:100px">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="productionUnitFeedCount" label="生产单位投料数" min-width="120px" align="center">
        </el-table-column>
        <el-table-column prop="productionUnitCount" label="生产单位库存数" min-width="120px" align="center">
        </el-table-column>
        <el-table-column :resizable="false" prop="productionUnitReceiveCount" label="生产单位发料数" min-width="110px" header-align="center">
          <template slot-scope="scope" v-if="scope.row.productionUnitReceiveCount!==null">
            <el-input-number size="mini" :controls="false" v-model="scope.row.productionUnitReceiveCount" :min="0" :max="scope.row.productionMaxCount"
              :precision="0" style="width:100px" @click.native.stop>
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" prop="remark" label="备注" width="130px" header-align="center">
          <template slot-scope="scope" v-if="scope.row.isSelect">
            <el-input size="mini" v-model="scope.row.remark" style="width:120px" @click.native.stop></el-input>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" fixed="right" type="selection" column-key="selection" :selectable="canSelect" align="center" width="40px"
          @click.native.stop></el-table-column>
      </el-table>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>

    <el-dialog fullscreen class="dialog-fullscreen" :title="i18n.getMsg('createIssueNote.dialogTitle.'+dialogType)" :visible.sync="openDialog"
      @closed="dialogClosed">
      <template v-if="openDialog">
        <out-to-order v-if="dialogType==='workshop'" :dept-and-work="saveData.deptAndWork" :to-order-material-data="selectMaterial"
          @after="issueSuccess">
        </out-to-order>
        <issue-out-order v-else-if="dialogType==='approvalOrder'" :materials="selectMaterial" :dropdown-option="dropdownOption"
          @issue-success="issueSuccess">
        </issue-out-order>
      </template>
    </el-dialog>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/searchBtnView.css",
    "/vueSystem/components/css/sysCommonSearch.css",
    "./css/outToOrder.css",
    "./css/issueOutOrder.css"
  ], [
    "/vueSystem/i18n/index.js",
    "/vueSystem/js/dropdownUtil.js",
    "/vueSystem/js/checkVaildUtil.js",
    "/vueSystem/components/sysCommonSearch.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/components/filterSelect.js",
    "/vueSystem/mixins/tablePaginationMixin.js"
  ]);

</script>
<script src="../utils/moduleUtil.js"></script>
<script src="./outToOrder.js"></script>
<script src="./issueOutOrder.js"></script>

<script type="text/javascript">
  var app = new Vue({
    el: '#app',
    mixins: [
      tablePaginationMixin()
    ],
    data: function () {
      var search = {
        materialName: '',
        materialType: '',
        model: '',
        color: '',
        providerName: '',
        materialDept: '',
        providerNo: '',
        companyOrderId: '',
        orderId: '',
        factoryNo: '',
        customerNo: '',
        isValid: '',
        hairFeedType: 1
      };
      return {
        loading: false,
        moment: moment,
        materialDataList: [],
        deptWorkshopList: [],
        checkData: [],
        materialData: {},
        searchField: ['materialName', 'materialType', 'model', 'color', 'providerName', 'providerNo', 'materialDept', 'companyOrderId',
          'orderId', 'factoryNo', 'customerNo'
        ],
        saveData: {
          deptAndWork: []
        },
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        dialogType: '',
        openDialog: false,
        selectMaterial: null,
        dropdownOption: {},
        i18n: i18n
      };
    },
    created: function () {
      this.setDeptAndWorkList();
    },
    methods: {
      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialDataList(true);
      },

      pageChange: function () {
        this.setMaterialDataList();
      },

      setMaterialDataList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }
        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        }
        postData = this.setPostData(postData, search);

        this.loading = true;
        var self = this;
        ajaxRequest("issueNote/getFeedMaterialData", postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var dataList = res.returnData;
          if (dataList === undefined) {
            self.$alert(res.info, '消息');
            self.loading = false;
            return;
          }

          self.formatData(dataList);
          var dataObject = _.groupBy(dataList, 'materialCode');
          var materialData = {};
          for (var materialCode in dataObject) {
            var materialCodeList = dataObject[materialCode];
            materialData[materialCode] = {
              count: materialCodeList[0].warehouseCount,
              productionUnitCount: materialCodeList[0].productionUnitCount
            };
          }
          self.materialDataList = dataList;
          self.materialData = materialData;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setPostData: function (postData, search) {
        var fields = ['orderId', 'companyOrderId', 'factoryNo', 'customerNo', 'materialName', 'materialType', 'model', 'color',
          'providerName', 'providerNo', 'isValid', 'hairFeedType'
        ];
        SysUtil.setPostData(postData, search, fields);

        if (postData.companyOrderId === undefined && postData.orderId === undefined &&
          postData.customerNo === undefined && postData.factoryNo === undefined) {
          postData.isQueryMaterial = 1;
        } else {
          postData.isQueryMaterial = 0;
        }

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }
        return postData;
      },
      formatData: function (dataList) {
        var len = dataList.length;
        for (var i = 0; i < len; i++) {
          var data = dataList[i];
          data.remark = '';
          data.model = data.modal;
          SysUtil.tableSetDeptData(data);

          var precision = SysUtil.getMaterialNumberPrecision(data.unit, 4);
          data.precision = precision;

          var orderId = data.orderId;
          var receiveCount = undefined,
            productionUnitReceiveCount = undefined;
          var isSelect;
          if (data.statusType !== 0) {
            receiveCount = null;
            productionUnitReceiveCount = null;
            isSelect = false;
          } else {
            var warehouseCount = data.warehouseCount,
              productionUnitCount = data.productionUnitCount;
            if (warehouseCount > 0 || productionUnitCount > 0) {
              if (warehouseCount <= 0) {
                receiveCount = null;
              } else {
                if (SysUtil.isEmpty(orderId)) {
                  data.receiveMaxCount = warehouseCount;
                } else {
                  data.receiveMaxCount = _.min([warehouseCount, data.receiveCount]);
                }
                receiveCount = data.receiveMaxCount;
              }

              if (!SysUtil.isEmpty(orderId)) {
                if (productionUnitCount <= 0) {
                  productionUnitReceiveCount = null;
                } else {
                  data.productionMaxCount = _.min([productionUnitCount, data.productionUnitFeedCount]);
                  productionUnitReceiveCount = data.productionMaxCount;
                }
              } else {
                productionUnitReceiveCount = null;
              }
              isSelect = receiveCount !== null || productionUnitReceiveCount !== null;
            } else {
              receiveCount = null;
              productionUnitReceiveCount = null;
              isSelect = false;
            }
          }

          var feedCount = data.feedCount;
          var feedTotal = data.feedTotal;
          var singleFeedCount;
          if (data.unit === '付') {
            singleFeedCount = 1;
          } else if (SysUtil.isEmpty(feedCount) || SysUtil.isEmpty(feedTotal) || data.type === 2) {
            singleFeedCount = null;
          } else {
            singleFeedCount = feedCount / feedTotal;
          }

          data.singleFeedCount = singleFeedCount;

          if (isSelect && !SysUtil.isEmpty(orderId)) {
            if (singleFeedCount === null || SysUtil.isEmpty(receiveCount)) {
              data.selfOutFuCount = undefined;
            } else {
              var selfOutFuCount = _.round(receiveCount / singleFeedCount, 4);
              data.selfOutFuCount = Math.floor(selfOutFuCount);
            }
          } else {
            data.selfOutFuCount = null;
          }

          data.receiveCount = receiveCount;
          data.productionUnitReceiveCount = productionUnitReceiveCount;
          data.isSelect = isSelect;

          var inSumPrice = data.inSumPrice;
          var inSumCount = data.inSumCount;
          var unitPrice;
          if (inSumCount === 0) {
            unitPrice = 0;
          } else {
            unitPrice = _.round(inSumPrice / inSumCount, 4);
          }
          data.unitPrice = unitPrice;
        }
      },

      checkOrder: function (selection) {
        this.checkData = selection;
      },

      setDeptAndWorkList: function () {
        var self = this;
        DropdownUtil.getDeptWorkshopUserList().then(function (deptWorkshopList) {
          self.deptWorkshopList = deptWorkshopList;
        }).catch(function () {
          self.deptWorkshopList = [];
        });
      },

      receiveCountChange: function (issue) {
        if (issue.selfOutFuCount === null) {
          return;
        }

        var singleFeedCount = issue.singleFeedCount;
        if (singleFeedCount === null) {
          return;
        }

        var receiveCount = issue.receiveCount;
        if (receiveCount === undefined) {
          issue.selfOutFuCount = 0;
          return;
        }

        var selfOutFuCount = receiveCount / singleFeedCount;
        selfOutFuCount = _.round(selfOutFuCount, 4);
        issue.selfOutFuCount = Math.floor(selfOutFuCount);
      },

      save: function (type) {
        var checkData = this.checkData;
        var materialData = this.materialData;
        var saveData = this.saveData;
        if (!ModuleUtil.checkIssueValid(type, checkData, materialData, saveData)) {
          return;
        }

        var postData = [];
        for (var i = 0; i < checkData.length; i++) {
          var data = checkData[i];
          if (!ModuleUtil.checkIssueRowValid(data)) {
            return;
          }

          var issuePostData = ModuleUtil.getIssuePostData(data, type, saveData);
          postData.pushArray(issuePostData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/saveWarehouseOut", {
          metailArray: JSON.stringify(postData)
        }).then(function (msg) {
          self.loading = false;
          self.$alert(msg, '信息');
          self.setMaterialDataList();
        }).catch(function () {
          self.loading = false;
        });
      },

      putToOutsource: function () {
        var checkData = this.checkData;
        if (!ModuleUtil.checkIssueValid('approvalOrder', checkData, this.materialData)) {
          return;
        }

        for (var i = 0; i < checkData.length; i++) {
          if (!ModuleUtil.checkIssueRowValid(checkData[i])) {
            return;
          }
        }

        this.selectMaterial = checkData;
        this.dialogType = 'approvalOrder';
        this.openDialog = true;
      },

      rowClick: function (row, column) {
        var columnKey = column.columnKey;
        if (['receiveCount', 'selfOutFuCount', 'productionUnitReceiveCount', 'remark', 'selection'].indexOf(columnKey) !== -1) {
          return;
        }

        if (row.orderId === null) {
          var deptAndWork = this.saveData.deptAndWork;
          if (deptAndWork.length === 0) {
            this.$alert('若要物料出库给订单,请先选择发料给车间的人员');
            return;
          }
          this.selectMaterial = row;
          this.dialogType = 'workshop';
          this.openDialog = true;
        }
      },

      dialogClosed: function () {
        this.dialogType = '';
        this.selectMaterial = null;
      },

      canSelect: function (row) {
        return row.isSelect;
      },

      issueSuccess: function () {
        this.openDialog = false;
        this.setMaterialDataList();
      },

      getCellClassName: function (option) {
        var column = option.column;
        var columnKey = column.columnKey;
        if (columnKey !== 'selection') {
          return;
        }
        var material = option.row;
        if (material.statusType === 1) {
          return 'purchaseOrderNotApproval';
        }

        var warehouseCount = material.warehouseCount;
        if (warehouseCount === null) {
          warehouseCount = 0;
        }
        var productionUnitCount = material.productionUnitCount;
        if (productionUnitCount === null) {
          productionUnitCount = 0;
        }
        if (warehouseCount === 0 && productionUnitCount === 0) {
          return 'materialCountIsNull';
        }
        return;
      },

      getSumPrice: function (issue) {
        var unitPrice = issue.unitPrice;
        var receiveCount = issue.receiveCount;
        if (receiveCount === null) {
          return;
        }
        if (receiveCount === undefined) {
          receiveCount = 0;
        }
        var sumPrice = unitPrice * receiveCount;
        return _.round(sumPrice, 4);
      }
    },
    components: {
      SysCommonSearch: SysCommonSearch,
      SearchBtnView: SearchBtnView,
      OutToOrder: OutToOrder,
      IssueOutOrder: IssueOutOrder
    }
  });

</script>

<style>
  .issue-note {
    padding: 10px 20px 5px;
    min-width: 800px;
    height: calc(100% - 15px);
    display: flex;
    flex-direction: column;
    overflow: auto;
  }

  .issue-note .materialDataListTable {
    margin-top: 10px;
    width: 100%;
    flex: 1;
    overflow: auto;
  }

  .issue-note .materialDataListTable .purchaseOrderNotApproval {
    background: #999;
  }

  .issue-note .materialDataListTable .materialCountIsNull {
    background: #dd514c;
  }

  .el-table .table-count {
    display: flex;
    text-overflow: ellipsis;
    overflow: hidden;
  }

</style>

</html>
